<script lang="tsx">
import { defineComponent, ref, watchEffect, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { getRegistrationInfoPageApi, getMatchListApi, getGroupListApi, getRegistrationInfoCountApi, exportRegistrationInfoApi, createRegistrationInfoApi, worksReviewApi, registrationReviewApi } from '#/api/competition/registration-info';
import { registrationStatusOptions, workStatusOptions } from './modules/registration-info/const';
import AddRegistrationInfo from './modules/registration-info/add-registration-info.vue';
import RegistrationAudit from './modules/registration-info/registration-audit.vue';
import TeamMembers from './modules/team-info/team-members.vue';
import { ClipboardCheck, UsersRound } from '@vben/icons';

export default defineComponent({
  name: 'RegistrationInfo',
  setup() {
    const registrationStatusMap: Record<number, string> = {
      0: $t('competition.registrationInfo.registrationStatusMap.0'),
      1: $t('competition.registrationInfo.registrationStatusMap.1'),
      2: $t('competition.registrationInfo.registrationStatusMap.2'),
      3: $t('competition.registrationInfo.registrationStatusMap.3')
    };
    const worksStatusMap: Record<number, string> = {
      0: $t('competition.registrationInfo.worksStatusMap.0'),
      1: $t('competition.registrationInfo.worksStatusMap.1'),
      2: $t('competition.registrationInfo.worksStatusMap.2'),
      3: $t('competition.registrationInfo.worksStatusMap.3')
    };
    const exportLoading = ref(false);
    const matchList = ref<any[]>([]);
    const groupList = ref<any[]>([]);
    const showAddRegistrationInfo = ref(false);
    const currentRegistrationInfoData = ref<any>({});
    const statistics = ref<any>({
      regTotalCount: 0,
      worksReviewPassCount: 0,
      worksSubmitCount: 0
    });
    const showMembers = ref(false);
    const showRegistrationAudit = ref(false);
    const submitLoading = ref(false);
    // 获取大赛列表
    const loadMatchList = async () => {
      try {
        const response = await getMatchListApi();
        matchList.value = response || [];
      } catch (error) {
      }
    };

    // 获取赛事组别列表
    const loadGroupList = async (compId: string) => {
      if (!compId) {
        groupList.value = [];
        return;
      }
      try {
        const response = await getGroupListApi({
          compId,
          curPage: 1,
          pageSize: 1000
        });
        groupList.value = response.data || [];
      } catch (error) {
      }
    };

    // 获取报名信息数量
    const loadRegistrationInfoCount = async (params: any = {}) => {
      try {
        const response = await getRegistrationInfoCountApi(params);
        return response;
      } catch (error) {
      }
    };

    // 查询配置
    const queryColumns = ref([
      {
        prop: 'compId',
        label: $t('competition.registrationInfo.compName'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.compName')]),
        options: [],
        onChange: (value: string) => {
          // 清空 groupId
          queryState.data.groupId = '';
          loadGroupList(value);
        }
      },
      {
        prop: 'groupId',
        label: $t('competition.registrationInfo.groupName'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.groupName')]),
        options: [],
      },
      {
        prop: 'teamName',
        label: $t('competition.teamName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.teamName')]),
      },
      {
        prop: 'organizationName',
        label: $t('competition.organizationName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.organizationName')]),
      },
      {
        prop: 'worksName',
        label: $t('competition.registrationInfo.worksName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.registrationInfo.worksName')]),
      },
      {
        prop: 'registrationStatus',
        label: $t('competition.registrationInfo.registrationStatus'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.registrationStatus')]),
        options: registrationStatusOptions,
      },
      {
        prop: 'worksStatus',
        label: $t('competition.registrationInfo.worksStatus'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.worksStatus')]),
        options: workStatusOptions,
      },
    ]);

    // 初始化加载大赛列表
    loadMatchList();

    const API = {
      get: (data: any) => {
        let params = { ...data };
        console.log('params', params);
        registrationCountQuery();
        return getRegistrationInfoPageApi(params);
      }
    };

    // 监听 matchList 变化，更新查询配置中的选项
    watchEffect(() => {
      if (queryColumns.value[0]) {
        queryColumns.value[0].options = matchList.value.map(item => ({
          label: item.matchName,
          value: item.id
        }));
      }
      if (queryColumns.value[1]) {
        queryColumns.value[1].options = groupList.value.map(item => ({
          label: item.name,
          value: item.id
        }));
      }
    });

    // 表格列配置
    const columns = [
      {
        type: 'index',
        label: $t('common.numberIdxTxt'),
        width: 60,
        align: 'center',
        prop: 'index'
      },
      {
        prop: 'compName',
        label: $t('competition.registrationInfo.compName'),
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.compName || '--';
        }
      },
      {
        prop: 'trackName',
        label: $t('competition.registrationInfo.trackName'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.trackName || '--';
        }
      },
      {
        prop: 'groupName',
        label: $t('competition.registrationInfo.groupName'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.groupName || '--';
        }
      },
      {
        prop: 'teamName',
        label: $t('competition.teamName'),
        minWidth: 150,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.teamName || '--';
        }
      },
      {
        prop: 'organizationName',
        label: $t('competition.organizationName'),
        minWidth: 150,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.organizationName || '--';
        }
      },
      {
        prop: 'worksName',
        label: $t('competition.registrationInfo.worksName'),
        minWidth: 150,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.worksName || '--';
        }
      },
      {
        prop: 'createTime',
        label: $t('competition.registrationInfo.createTime'),
        minWidth: 170,
        formatter: (row: any) => {
          return row.createTime ? row.createTime.replace('T', ' ').substring(0, 19) : '--';
        }
      },
      {
        prop: 'registrationStatus',
        label: $t('competition.registrationInfo.registrationStatus'),
        minWidth: 100,
        formatter: (row: any) => {
          const status = Number(row.registrationStatus);
          return <span class={status === 2 ? 'text-green-600' : status === 3 ? 'text-red-600' : ''}>
            {registrationStatusMap[status] || '--'}
          </span>;
        }
      },
      {
        prop: 'worksStatus',
        label: $t('competition.registrationInfo.worksStatus'),
        minWidth: 100,
        formatter: (row: any) => {
          const status = Number(row.worksStatus);
          return <span class={status === 2 ? 'text-green-600' : status === 3 ? 'text-red-600' : ''}>
            {worksStatusMap[status] || '--'}
          </span>;
        }
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'audit',
        width: 60,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('competition.registrationInfo.worksDetail')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                type="primary"
                icon={ClipboardCheck}
                onClick={() => tableHandle('audit', row, index)}
              >
              </el-button>
            </el-tooltip>
          );
        },
      },
      {
        key: 'usersView',
        width: 60,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('competition.teamInfo.membersInfo')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                icon={UsersRound}
                type="primary"
                onClick={() => tableHandle('usersView', row, index)}
              >
              </el-button>
            </el-tooltip>
          );
        },
      },
    ];

    // 自定义操作处理
    const handleCommand = (action: string, row: any, index?: number) => {
      console.log('action', action)
      if (action === 'usersView') {
        // 查看详情
        showMembers.value = true;
        currentRegistrationInfoData.value = row;
      } else if (action === 'audit') {
        // 编辑
        showRegistrationAudit.value = true;
        currentRegistrationInfoData.value = row;
      }
    };

    // 导出功能
    const handleExport = async () => {
      const params = {
        idList: selection.value.map((item: any) => item.id),
        ...queryState.data
      }
      try {
        exportLoading.value = true;
        const response = await exportRegistrationInfoApi(params) as any;
        // 验证响应是否为有效的Excel文件
        if (!response || response.data.size === 0) {
          throw new Error($t('common.exportFailed'));
        }

        // 检查MIME类型
        const validTypes = [
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'application/vnd.ms-excel',
          'application/octet-stream'
        ];

        if (!validTypes.includes(response.data.type)) {
          console.warn('Unexpected file type:', response.data.type);
        }

        // 创建下载链接
        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;

        // 根据MIME类型设置文件名
        const timestamp = new Date().toISOString().split('T')[0];
        let fileName = `团队信息_${timestamp}`;

        if (response.data.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          fileName += '.xlsx';
        } else if (response.data.type === 'application/vnd.ms-excel') {
          fileName += '.xls';
        } else {
          // 默认使用.xlsx扩展名
          fileName += '.xlsx';
        }

        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        exportLoading.value = false;
        ElMessage.success($t('common.exportSuccess'));
      } catch (error) {
        exportLoading.value = false;
        ElMessage.error($t('common.exportFailed'));
      }
    };

    const handleAddRegistrationInfo = () => {
      showAddRegistrationInfo.value = true;
    };

    const { queryState, render, tableHandle, selection, getTableData } = usePage({
      API,
      operateProps: {
        fixed: 'right',
      },
      columns,
      queryColumns: queryColumns.value,
      commands,
      handleCommand,
    });

    const handleConfirm = (data: any) => {
      console.log('data', data)
      getTableData();
      showAddRegistrationInfo.value = false;
    }

    const handleUpdateRegistrationStatus = (params: any) => {
      submitLoading.value = true;
      registrationReviewApi(params).then(res => {
        console.log('res', res)
        getTableData();
        showRegistrationAudit.value = false;
      }).finally(() => {
        submitLoading.value = false;
      })
    }

    const handleUpdateWorksStatus = (params: any) => {
      submitLoading.value = true;
      worksReviewApi(params).then(res => {
        console.log('res', res)
        getTableData();
        showRegistrationAudit.value = false;
      }).finally(() => {
        submitLoading.value = false;
      })
    }

    onMounted(() => {
      registrationCountQuery();
    })

    const registrationCountQuery = async () => {
      statistics.value = await loadRegistrationInfoCount(queryState.data);
    }

    return () => (
      <div class="registration-info-page">
        {
          render({
            header: (
              <div class="flex justify-between items-center">
                <div class="flex gap-2">
                  <el-button type="primary" onClick={() => handleAddRegistrationInfo()}>
                    {$t('common.addTxt')}
                  </el-button>
                  <el-button onClick={handleExport} loading={exportLoading.value}>
                    {$t('common.exportTxt')}
                  </el-button>
                </div>
                <div class="flex gap-4">
                  <div class="bg-[#F3F3F3] py-[5px] px-[12px] rounded-[4px] flex items-center justify-center">
                    <div class="text-[14px] text-[#595959] mr-[20px]">{$t('competition.registrationInfo.regTotalCount')}</div>
                    <div class="text-[16px] text-500 text-[#191919]">{statistics.value?.regTotalCount ?? '--'}</div>
                  </div>
                  <div class="bg-[#0067D114] py-[5px] px-[12px] rounded-[4px] flex items-center justify-center">
                    <div class="text-[14px] text-[#595959] mr-[20px]">{$t('competition.registrationInfo.worksSubmitCount')}</div>
                    <div class="text-[16px] text-500 text-[#191919]">{statistics.value?.worksSubmitCount ?? '--'}</div>
                  </div>
                  <div class="bg-[#30A46C14] py-[5px] px-[12px] rounded-[4px] flex items-center justify-center">
                    <div class="text-[14px] text-[#595959] mr-[20px]">{$t('competition.registrationInfo.worksAuditCount')}</div>
                    <div class="text-[16px] text-500 text-[#191919]">{statistics.value?.worksReviewPassCount ?? '--'}</div>
                  </div>
                </div>
              </div>
            ),
            table: {
              prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
            }
          })
        }
        <AddRegistrationInfo
          modelValue={showAddRegistrationInfo.value}
          onUpdate:modelValue={(val: boolean) => showAddRegistrationInfo.value = val}
          onCancel={() => showAddRegistrationInfo.value = false}
          onConfirm={handleConfirm}
        />
        <TeamMembers
          modelValue={showMembers.value}
          onUpdate:modelValue={(val: boolean) => showMembers.value = val}
          onCancel={() => showMembers.value = false}
          teamData={currentRegistrationInfoData.value}
        />
        <RegistrationAudit
          submitLoading={submitLoading.value}
          registrationStatusMap={registrationStatusMap}
          worksStatusMap={worksStatusMap}
          modelValue={showRegistrationAudit.value}
          onUpdate:modelValue={(val: boolean) => showRegistrationAudit.value = val}
          onCancel={() => showRegistrationAudit.value = false}
          data={currentRegistrationInfoData.value}
          onUpdate:registrationStatus={handleUpdateRegistrationStatus}
          onUpdate:worksStatus={handleUpdateWorksStatus}
        />
      </div>
    );
  }
});
</script>

<style lang="scss" scoped>
.registration-info-page {
  .text-green-600 {
    color: #059669;
  }

  .text-red-600 {
    color: #dc2626;
  }
}
</style>
